package me.sealer.utils;

import com.alibaba.fastjson.JSON;
import me.sealer.model.Location;
import me.sealer.model.LocationResult;

/**
 * Created by sealer on 10-31-2017.
 */
public class LocationUtil {
    /**
     * 根据外网IP查询当地位置信息
     * @param ip
     * @return
     */
    public static String retrieveLocationJsonStringByIp(String ip) {
        String preUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=";
        try {
            String weatherInfo = IpUtil.retrieveWebPage(preUrl + ip);
            return StringUtil.isNullOrEmpty(weatherInfo) ? null : weatherInfo.trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将位置json格式字符串转化为Location对象
     * @param strLocation
     * @return
     */
    public static Location fromJson2Location(String strLocation) {
        LocationResult locationResult = JSON.parseObject(strLocation, LocationResult.class);
        System.out.println(locationResult);
        Location location = null;
        if (0 ==locationResult.getCode()) {
            location = locationResult.getData();
        }
        return location;
    }

    /**
     * 获取Location对象
     * @param ip
     * @return
     */
    public static Location retrieveLocationByIp(String ip) {
        String strLocation = retrieveLocationJsonStringByIp(ip);
        return fromJson2Location(strLocation);
    }
}
